package com.liming.server.service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liming.server.domain.User;
import com.liming.server.domain.UserExample;
import com.liming.server.dto.LoginUserDto;
import com.liming.server.dto.ResourceDto;
import com.liming.server.dto.UserDto;
import com.liming.server.dto.PageDto;
import com.liming.server.exception.BusinessException;
import com.liming.server.exception.BusinessExceptionCode;
import com.liming.server.mapper.UserMapper;
import com.liming.server.mapper.my.MyUserMapper;
import com.liming.server.util.CopyUtil;
import com.liming.server.util.UuidUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;

@Service
public class UserService {

    private static final Logger LOG = LoggerFactory.getLogger(UserService.class);

    @Resource
    private UserMapper userMapper;

    @Resource
    private MyUserMapper myUserMapper;

    public void list(PageDto pageDto){
        PageHelper.startPage(pageDto.getPage(),pageDto.getSize());
        UserExample userExample = new UserExample();
        List<User> userList = userMapper.selectByExample(userExample);
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        pageDto.setTotal(pageInfo.getTotal());
        //将userList通过CopyUtil.copyList()方法复制给userDtoList
        List<UserDto> userDtoList =CopyUtil.copyList(userList,UserDto.class);
        pageDto.setList(userDtoList);
    }

    public void save(UserDto userDto){
        //将userDto通过CopyUtil.copy()方法复制给User
        User user = CopyUtil.copy(userDto, User.class);
        if(StringUtils.isEmpty(userDto.getId())){
            this.insert(user);
        }else{
            this.update(user);
        }
    }

    private void insert(User user){
        user.setId(UuidUtil.getShortUuid());
        User userDb = this.selectByLoginName(user.getLoginName());
        if(userDb != null){
            throw new BusinessException(BusinessExceptionCode.USER_LOGIN_NAME_EXIST);
        }

        userMapper.insert(user);
    }

    private void update(User user){
        user.setPassword(null);
        //updateByPrimaryKeySelective会对字段进行非空判断，再更新，如果值为空就不更新，原理就是利用mybatis的if拼成动态sql
        userMapper.updateByPrimaryKeySelective(user);
    }

    public void delete(String id){
        userMapper.deleteByPrimaryKey(id);
    }

    /**
     * 根据登录名查询用户信息
     * @param loginName
     * @return
     */
    public User selectByLoginName(String loginName){
        UserExample example = new UserExample();
        example.createCriteria().andLoginNameEqualTo(loginName);
        List<User> userList = userMapper.selectByExample(example);
        //判断list是不是为空
        if(CollectionUtils.isEmpty(userList)){
            return null;
        }else {
            return userList.get(0);
        }
    }

    /**
     * 重置密码
     * @param userDto
     */
    public void savePassword(UserDto userDto){
        User user = new User();
        user.setId(userDto.getId());
        user.setPassword(userDto.getPassword());
        userMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 用户登录
     * @param userDto
     */
    public LoginUserDto login(UserDto userDto){
        User user = selectByLoginName(userDto.getLoginName());
        if(user == null){
            LOG.info("用户不存在,{}",userDto.getId());
            throw new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
        }else {
            if(user.getPassword().equals(userDto.getPassword())){
                LOG.info("登录成功");
                LoginUserDto loginUserDto = CopyUtil.copy(user, LoginUserDto.class);
                //为登录用户读取权限
                setAuth(loginUserDto);
                return loginUserDto;
            }else {
                LOG.info("密码错误，输入密码{}，数据库密码：{}",userDto.getPassword(),user.getPassword());
                throw new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
            }
        }
    }

    /**
     * 为登录用户读取权限
     * @param loginUserDto
     */
    private void setAuth(LoginUserDto loginUserDto){
        List<ResourceDto> resourceDtoList = myUserMapper.findResources(loginUserDto.getId());
        loginUserDto.setResources(resourceDtoList);

        //整理所有权限的请求，用于接口拦截
        HashSet<String> requestSet = new HashSet<>();
        if(!CollectionUtils.isEmpty(resourceDtoList)){

            for (int i = 0; i < resourceDtoList.size(); i++) {
                ResourceDto resourceDto = resourceDtoList.get(i);
                String arrayString = resourceDto.getRequest();
                List<String> requestList = JSON.parseArray(arrayString, String.class);
                if(!CollectionUtils.isEmpty(requestList)){
                    requestSet.addAll(requestList);
                }
            }
        }
        LOG.info("有的权限的请求：{}" ,requestSet);
        loginUserDto.setRequests(requestSet);
    }


}